<!-- 员工管理 -->

<template>
  <div class="container">
    <div class="app-container" v-loading="isLoading">
      <div class="left">
        <el-input style="margin-bottom:10px" type="text" prefix-icon="el-icon-search" size="small"
          placeholder="输入员工姓名全员搜索" v-model.trim="queryParams.keyword" @input="changeValue" />
        <!-- 树形组件 -->
        <el-tree ref="deptTree" node-key="id" :data="depts" :props="defaultProps" default-expand-all
          :expand-on-click-node="false" highlight-current @current-change="currentChange" />
      </div>
      <div class="right">
        <el-row class="opeate-tools" type="flex" justify="end">
          <el-button v-permission="'add-employee'" size="mini" type="primary"
            @click="$router.push('/employee/detail')">添加员工</el-button>
          <el-button size="mini" @click="showExcelDialog = true">excel导入</el-button>
          <el-button size="mini" @click="excelDown">excel导出</el-button>
        </el-row>
        <!-- 表格组件 -->
        <el-table :data="userList">
          <el-table-column prop="staffPhoto" align="center" label="头像">
            <template v-slot="{ row }">
              <el-avatar v-if="row.staffPhoto" size="medium" :src="row.staffPhoto"></el-avatar>
              <span v-else class="username">{{ row.username?.charAt(0) }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="username" label="姓名" />
          <el-table-column prop="mobile" label="手机号" sortable />
          <el-table-column prop="workNumber" label="工号" sortable />
          <el-table-column prop="formOfEmployment" label="聘用形式">
            <template v-slot="{ row }">
              <span v-if="row.formOfEmployment === 1">正式</span>
              <span v-else-if="row.formOfEmployment === 2">非正式</span>
              <span v-else>无</span>
            </template>
          </el-table-column>
          <el-table-column prop="departmentName" label="部门" />
          <el-table-column prop="timeOfEntry" label="入职时间" sortable />
          <el-table-column label="操作" width="280px">
            <template v-slot="{ row }">
              <el-button size="mini" type="text" @click="$router.push(`/employee/detail/${row.id}`)">查看</el-button>
              <el-button size="mini" type="text" @click="roleBtn(row.id)">角色</el-button>
              <el-popconfirm title="是否删除此员工？" @onConfirm="delRole(row.id)">
                <el-button slot="reference" size="mini" type="text" style="margin-left: 10px;">删除</el-button>
              </el-popconfirm>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <el-row style="height: 60px" align="middle" type="flex" justify="end">
          <el-pagination layout="total,prev, pager, next" :total="total" :current-page="queryParams.page"
            :page-size="queryParams.pagesize" @current-change="changePage" />
        </el-row>
        <!-- 员工导入 -->
        <ImportExcel :showExcelDialog.sync="showExcelDialog" @uploadSuccess="getEmployeeList"></ImportExcel>
        <!-- 权限添加 -->
        <el-dialog :visible.sync="showRoleDialog" title="分配角色">
          <el-checkbox-group v-model="roleIds">
            <!-- 放置n个的checkbox  要执行checkbox的存储值 item.id-->
            <el-checkbox v-for="item in roleList" :key="item.id" :label="item.id">{{ item.name }}</el-checkbox>
          </el-checkbox-group>
          <el-row slot="footer" type="flex" justify="center">
            <el-col :span="6">
              <el-button type="primary" size="mini" @click="btnRoleOK">确定</el-button>
              <el-button size="mini" @click="showRoleDialog = false">取消</el-button>
            </el-col>
          </el-row>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script>
import { getDepartmentAPI } from "@/api/department.js"
import { listToTreeData } from "@/utils/index.js"
import {
  getEmployeeListAPI, staffExportAPI, delStaffAPI, getEnableRoleListAPI, getStaffAPI, userAssignRolesAPI
} from "@/api/employee.js"
import FileSaver from 'file-saver'
import ImportExcel from "./components/import-excel.vue"

export default {
  name: 'Employee',
  data() {
    return {
      isLoading: true,
      depts: [], // 组织数据
      defaultProps: {
        label: 'name',
        children: 'children'
      },
      // 存储查询参数
      queryParams: {
        departmentId: null,  // 当前选中节点id
        page: 1, // 当前页码
        pagesize: 10,  // 当前页码显示数据条数
        keyword: '' // 模糊查询名
      },
      userList: [], // 员工列表
      roleIds: [], // 启用角色列表
      total: 0, // 员工总数
      showExcelDialog: false, // 控制excel的弹层显示和隐藏
      showRoleDialog: false, // 控制角色弹层的显示
      roleList: [],  // 角色列表
      currentUserId: null, // 用来记录当前点击的用户id
    }
  },
  components: {
    ImportExcel
  },
  created() {
    this.getDepartment()
  },
  methods: {
    // 获取部门数据
    async getDepartment() {
      // 递归方法 将列表转化成树形
      this.depts = listToTreeData(await getDepartmentAPI(), 0)
      this.queryParams.departmentId = this.depts[0].id
      this.$nextTick(() => {
        // 树渲染完毕后 设置当前选中状态
        this.$refs.deptTree.setCurrentKey(this.queryParams.departmentId)
      })
      this.getEmployeeList()
    },
    // 获取员工列表
    async getEmployeeList() {
      this.isLoading = true
      const { rows, total } = await getEmployeeListAPI(this.queryParams)
      this.userList = rows
      this.total = total
      this.isLoading = false
    },
    // 切换节点
    currentChange(node) {  // node：当前节点的数据
      this.queryParams.departmentId = node.id // 记录当前点击节点id
      this.queryParams.page = 1 // 设置第一页
      this.getEmployeeList()
    },
    // 切换页码
    changePage(newPage) {
      this.queryParams.page = newPage // 赋值新页码
      this.getEmployeeList() // 查询数据
    },
    // 模糊查询
    changeValue() {
      this.timer && clearTimeout(this.timer)  // 清除定时器
      this.timer = setTimeout(() => {  // 输入有值时开启定时器
        this.queryParams.page = 1
        this.getEmployeeList()
      }, 300)
    },
    // 员工excel导出
    excelDown() {
      this.$confirm('导出可能需要一定时间，确定导出嘛？', '提示', {
        confirmButtonText: '导出',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const loading = this.$loading({ // 开启加载中动画
          lock: true,
          text: '员工信息导出中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        });
        const result = await staffExportAPI() // 导出所有的员工接口
        FileSaver.saveAs(result, '员工信息表.xlsx') // 下载文件
        this.$message.success("员工导出成功")
        loading.close();  // 关闭加载中动画
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '取消导出'
        });
      });
    },
    // 删除员工
    async delRole(id) {
      await delStaffAPI(id)
      if (this.userList.length === 1 && this.queryParams.page > 1) {  // 当前页最后数据
        this.queryParams.page--
      }
      this.getEmployeeList()  // 更新员工数据
      this.$message.success('删除员工成功')
    },
    // 角色按钮
    async roleBtn(id) {
      this.roleList = await getEnableRoleListAPI()
      this.currentUserId = id
      const { roleIds } = await getStaffAPI(id)
      this.roleIds = roleIds  // 启用角色
      this.showRoleDialog = true
    },
    // 分配角色
    async btnRoleOK() {
      await userAssignRolesAPI({
        id: this.currentUserId,
        roleIds: this.roleIds
      })
      this.$message.success('分配用户角色成功')
      this.showRoleDialog = false
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  background: #fff;
  display: flex;

  .left {
    width: 280px;
    padding: 20px;
    border-right: 1px solid #eaeef4;
  }

  .right {
    flex: 1;
    padding: 20px;

    .opeate-tools {
      margin: 10px;
    }

    .username {
      height: 30px;
      width: 30px;
      line-height: 30px;
      text-align: center;
      border-radius: 50%;
      color: #fff;
      background: #04C9BE;
      font-size: 12px;
      display: inline-block;
    }
  }
}
</style>